package com.bigdata.appliance.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bigdata.appliance.common.exception.BusinessException;
import com.bigdata.appliance.common.exception.ResponseCode;
import com.bigdata.appliance.common.pojo.GoodsOrderInfo;
import com.bigdata.appliance.common.pojo.PageResult;
import com.bigdata.appliance.entity.Goods;
import com.bigdata.appliance.entity.OrderDetail;
import com.bigdata.appliance.entity.Orders;
import com.bigdata.appliance.entity.User;
import com.bigdata.appliance.mapper.GoodsMapper;
import com.bigdata.appliance.mapper.OrderDetailMapper;
import com.bigdata.appliance.mapper.OrdersMapper;
import com.bigdata.appliance.mapper.UserMapper;
import com.bigdata.appliance.service.IOrdersService;
import com.bigdata.appliance.vo.req.DoPayReqVO;
import com.bigdata.appliance.vo.req.GetBusinessmanOrderReqVO;
import com.bigdata.appliance.vo.req.PageOrdersReqVO;
import com.bigdata.appliance.vo.req.UpdateOrderStatusReqVO;
import com.bigdata.appliance.vo.resp.GetBusinessmanOrderRespVO;
import com.bigdata.appliance.vo.resp.PageOrdersRespVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author appliance-shop
 * @since 2023-12-24
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private UserMapper userMapper;

    @Transactional
    @Override
    public void doPay(DoPayReqVO vo) {
        Orders orders = new Orders();
        orders.setUserId(vo.getUserId());
        orders.setAddressId(vo.getAddressId());
        orders.setStatus(2);
        orders.setCreateTime(LocalDateTime.now());
        orders.setUpdateTime(LocalDateTime.now());
        int insertOrder = ordersMapper.insert(orders);
        if (insertOrder !=1){
            throw new BusinessException(ResponseCode.OPERATION_ERROR.getCode(), ResponseCode.OPERATION_ERROR.getMessage());
        }
        BigDecimal totalPrice = new BigDecimal(0);
        for (GoodsOrderInfo goods : vo.getGoodsIds()) {
            Goods goods_info = goodsMapper.selectById(goods.getGoodsId());
            BigDecimal goodsTotalPrice = goods_info.getPrice().multiply(new BigDecimal(goods.getGoodsNum()));
            totalPrice = totalPrice.add(goodsTotalPrice);
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orders.getId());
            orderDetail.setGoodsId(goods.getGoodsId());
            orderDetail.setGoodsNum(goods.getGoodsNum());
            int insertOrderDetail = orderDetailMapper.insert(orderDetail);
            if (insertOrderDetail !=1){
                throw new BusinessException(ResponseCode.OPERATION_ERROR.getCode(), ResponseCode.OPERATION_ERROR.getMessage());
            }
            User businessUser = userMapper.selectById(goods_info.getUserId());
            businessUser.setWallet(businessUser.getWallet().add(goodsTotalPrice));
            int result = userMapper.updateById(businessUser);
            if (result !=1){
                throw new BusinessException(ResponseCode.OPERATION_ERROR.getCode(), ResponseCode.OPERATION_ERROR.getMessage());
            }
            goods_info.setStock(goods_info.getStock() - goods.getGoodsNum());
            int resultGoods = goodsMapper.updateById(goods_info);
            if (resultGoods !=1){
                throw new BusinessException(ResponseCode.OPERATION_ERROR.getCode(), ResponseCode.OPERATION_ERROR.getMessage());
            }
        }
        User user = userMapper.selectById(vo.getUserId());
        if(user.getWallet().compareTo(totalPrice) < 0){
            throw new BusinessException(ResponseCode.BALANCE_NOT_ENOUGH_EXISTS.getCode(), ResponseCode.BALANCE_NOT_ENOUGH_EXISTS.getMessage());
        }
        user.setWallet(user.getWallet().subtract(totalPrice));
        int result = userMapper.updateById(user);
        if (result !=1){
            throw new BusinessException(ResponseCode.OPERATION_ERROR.getCode(), ResponseCode.OPERATION_ERROR.getMessage());
        }
        
    }


    @Transactional
    @Override
    public void updateOrderStatus(UpdateOrderStatusReqVO vo) {
        Orders orders = ordersMapper.selectById(vo.getId());
        orders.setStatus(vo.getStatus());
        int result = ordersMapper.updateById(orders);
        if (result !=1){
            throw new BusinessException(ResponseCode.OPERATION_ERROR.getCode(), ResponseCode.OPERATION_ERROR.getMessage());
        }
    }

    @Override
    public PageResult<PageOrdersRespVO> pageOrders(PageOrdersReqVO vo) {
        IPage<PageOrdersRespVO> result = ordersMapper.selectPageOrders(new Page<>(vo.getCurrent(), vo.getSize()), vo);
        return PageResult.getPage(result.getRecords(),result.getTotal());
    }

    @Override
    public List<GetBusinessmanOrderRespVO> getBusinessmanOrder(GetBusinessmanOrderReqVO vo) {
        return orderDetailMapper.selectUserOrder(vo);
    }
}
